﻿using System.Net;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Xman.WebApi.Filters.Model;

namespace Xman.WebApi.Filters;
public class CustomExceptionAttribute : IAsyncExceptionFilter
{
    private readonly ILogger<CustomExceptionAttribute> _logger;

    public CustomExceptionAttribute(ILogger<CustomExceptionAttribute> logger)
    {
        _logger = logger;
    }
    public Task OnExceptionAsync(ExceptionContext context)
    {
        switch (context.Exception)
        {
            case CustomException:
                {
                    //自定义异常
                    context.Result = new OkObjectResult(new ResultWrapper(StatusCodes.Status400BadRequest, context.Exception.Message));
                    break;
                }
            case CustomContinueException:
                {
                    //异常后需要前端继续处理的
                    context.Result = new OkObjectResult(new ResultWrapper(StatusCodes.Status401Unauthorized, context.Exception.Message));
                    break;
                }
            default:
                {
                    //未捕获的异常
                    context.Result = new ObjectResult(new ResultWrapper((int)HttpStatusCode.InternalServerError, context.Exception.Message));
                    _logger.LogError(context.Exception.ToString());
                    break;
                }
        }
        context.ExceptionHandled = true;
        return Task.CompletedTask;
    }
}
